package com.laolu.icon.controller;

import com.laolu.icon.utils.MyBackup;
import com.laolu.icon.utils.MyRestore;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TextField;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

@Slf4j
public class MainWindowController {
	@FXML
	public TextField backupDirectory;
	@FXML
	public TextField backupFile;
	
	@FXML
	public void selectBackupDirectory(ActionEvent actionEvent) {
		
		DirectoryChooser chooser = new DirectoryChooser();
		chooser.setTitle("选择备份路径");
		chooser.setInitialDirectory(new java.io.File("E:\\"));
		File selectedDirectory = chooser.showDialog(backupDirectory.getScene().getWindow());
		if (selectedDirectory != null) {
			backupDirectory.setText(selectedDirectory.getAbsolutePath());
		}
	}
	
	@FXML
	public void backup(ActionEvent actionEvent) {
		String path = backupDirectory.getText();
		if (!validateBackupDirectory(path)) {
			showErrorMessage("请选择正确的备份路径");
			return;
		}
		MyBackup myBackup = new MyBackup();
		try {
			myBackup.backup(path);
		} catch (Exception e) {
			log.error("备份失败", e);
			showErrorMessage("备份失败");
		}
		
	}
	
	@FXML
	public void restore(ActionEvent actionEvent) {
		String path = backupFile.getText();
		if (!validateBackupFile(path)) {
			showErrorMessage("请选择正确的备份文件");
		}
		MyRestore myRestore = new MyRestore();
		try {
			myRestore.restore(path, true);
		} catch (Exception e) {
//				throw new RuntimeException(e);
			showErrorMessage("恢复失败");
			log.error("恢复失败", e);
		}
	}
	
	private boolean validateBackupFile(String path) {
		File file = new File(path);
		return file.exists() && file.isFile();
	}
	
	@FXML
	public void selectBackupFile(ActionEvent actionEvent) {
		FileChooser chooser = new FileChooser();
		chooser.setTitle("选择备份文件");
		chooser.getExtensionFilters().addAll(
				new FileChooser.ExtensionFilter("文本文件", "*.txt"),
				new FileChooser.ExtensionFilter("所有文件", "*.*"));
		chooser.setInitialDirectory(new java.io.File("E:\\"));
		File selectedFile = chooser.showOpenDialog(backupFile.getScene().getWindow());
		if (selectedFile != null) {
			backupFile.setText(selectedFile.getAbsolutePath());
		}
	}
	
	private boolean validateBackupDirectory(String path) {
		File file = new File(path);
		return file.exists() && file.isDirectory();
	}
	
	private void showErrorMessage(String message) {
		Alert alert = new Alert(Alert.AlertType.ERROR);
		alert.setHeaderText(message);
		alert.setTitle("Error");
		alert.showAndWait();
	}
	
}
